package com.xsir.ditan.miniprogram.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author user
 * @date 2021/2/1
 */
@Slf4j
@Component
public class ResponseResultInterceptor implements HandlerInterceptor {
    /**
     * 标记名称
     */
    private final static String RESPONSE_NEED_WRAP = "RESPONSE-NEED-WRAP";
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理方法
        if(handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            // 判断类对象或方法是否有@ResponseResult注解
            if(clazz.isAnnotationPresent(ResponseResult.class) || method.isAnnotationPresent(ResponseResult.class)) {
                // 设置此请求返回体需要包装，向下传递，在ResponseBodyAdvice接口进行判断
                log.debug("开始设置包装标记...");
                request.setAttribute(RESPONSE_NEED_WRAP, ResponseResult.class);
            }
        }
        
        return true;
    }
}
